# routers/variables_router.py
import os
from typing import List

from fastapi import APIRouter, Query, Depends, HTTPException

from Logs.log_handle import get_log
from schemas.variables_schemas import (
    create_localvariable_in_db,
    select_localvariable_in_db,
    del_localvariables_id_and_ids,
    update_localvariables_in_db,
    create_globalvariable_in_db,
    select_globalvariable_in_db,
    del_globalvariables_id_and_ids,
    update_globalvariables_in_db, LocalVariableCreate, LocalVariableResponse, GlobalVariableCreate,
)
from tools.decorators import return_response

# 初始化日志对象
log = get_log(os.path.split(__file__)[-1])

# 创建路由实例，统一前缀为 /variables
router = APIRouter(prefix="/variables", tags=["变量分配"])


# ---------------------------- LocalVariable API端点定义 ----------------------------
@router.post("/create_local_variable")
@return_response()
async def create_local_variable(local: LocalVariableCreate):
    """
    创建局部变量
    :param local: 通过请求体传递的数据
    :return: 创建成功的详情
    """
    log.info(f"收到创建局部变量请求，数据: {local.dict()}")
    result = create_localvariable_in_db(local)
    log.info(f"局部变量创建成功，返回数据: {result}")
    return result


@router.get("/get_local_variables")
@return_response()
async def get_local_variables(
        page: int = Query(1, description="页码"),
        size: int = Query(10, description="每页数据量"),
        local: LocalVariableCreate = Depends()
):
    """
    分页获取局部变量列表
    :param page: 当前页码，默认 1
    :param size: 每页数据量，默认 10
    :param local: 其他的筛选条件
    :return: 分页后的局部变量列表
    """
    log.info(f"获取所有局部变量，分页参数：page={page}, size={size}, 筛选条件：{local.dict()}")
    result = select_localvariable_in_db(page, size, local)
    log.info(f"查询结果返回，共 {len(result)} 条记录")
    return result


@router.post("/delete_local_variable")
@return_response()
async def delete_local_variable(ids: List[int]):
    """
    逻辑删除局部变量（支持批量删除）
    :param ids: 需要删除的局部变量 ID 列表
    """
    log.info(f"接收到删除请求，ids: {ids}")
    if not ids:
        log.error("ids 不能为空")
        raise HTTPException(status_code=400, detail="ids 不能为空")
    result = del_localvariables_id_and_ids(ids)
    log.info(f"删除操作完成，成功删除 {len(ids)} 条局部变量")
    return result


@router.post("/update_local_variable")
@return_response()
async def update_local_variable(local: LocalVariableResponse):
    """
    更新局部变量数据
    :param local: 更新后的局部变量数据
    """
    result = update_localvariables_in_db(local)
    return result


# ---------------------------- GlobalVariable API端点定义 ----------------------------
@router.post("/create_global_variable")
@return_response()
async def create_global_variable(global_var: GlobalVariableCreate):
    """
    创建全局变量
    :param global_var: 通过请求体传递的数据
    :return: 创建成功的详情
    """
    log.info(f"收到创建全局变量请求，数据: {global_var.dict()}")
    result = create_globalvariable_in_db(global_var)
    log.info(f"全局变量创建成功，返回数据: {result}")
    return result


@router.get("/get_global_variables")
@return_response()
async def get_global_variables(
        page: int = Query(1, description="页码"),
        size: int = Query(10, description="每页数据量"),
        global_var: GlobalVariableCreate = Depends()
):
    """
    分页获取全局变量列表，如果没有匹配项则创建一个并返回
    """
    result = select_globalvariable_in_db(page, size, global_var)
    log.info(f"分页查询全局变量结果: {result}")

    if not result['data']:
        log.info("未查询到全局变量，尝试创建一个新的...")
        create_globalvariable_in_db(global_var)
        print(global_var.global_key)
        result_create = select_globalvariable_in_db(page, size, global_var)
        return result_create

    return result


@router.post("/delete_global_variable")
@return_response()
async def delete_global_variable(global_ids: List[int]):
    """
    逻辑删除全局变量（支持批量删除）
    :param global_ids: 需要删除的全局变量 ID 列表
    """
    log.info(f"接收到删除请求，global_ids: {global_ids}")
    if not global_ids:
        log.error("global_ids 不能为空")
        raise HTTPException(status_code=400, detail="global_ids 不能为空")
    result = del_globalvariables_id_and_ids(global_ids)
    log.info(f"删除操作完成，成功删除 {len(global_ids)} 条全局变量")
    return result


@router.post("/update_global_variable")
@return_response()
async def update_global_variable(global_id: int, global_var: GlobalVariableCreate):
    """
    更新全局变量数据
    :param global_id: 需要更新的全局变量 ID
    :param global_var: 更新后的全局变量数据
    """
    log.info(f"接收到更新请求，global_id: {global_id}, 更新数据: {global_var.dict()}")
    result = update_globalvariables_in_db(global_id, global_var)
    log.info(f"更新全局变量成功，global_id: {global_id}, 更新后数据: {result}")
    return result
